import { App, createApp, onUnmounted } from 'vue';
import FPopover from './popover.component';

export interface PopoverServiceOptions {
    reference: any;
    popupHost: any;
    popupRightBoundary: any;
    popupOffsetX: any;
    content?: { render(): JSX.Element };
    render?(): any;
    onClickCallback?(): void;
}

function getContentRender(props: PopoverServiceOptions) {
    if (props.content && props.content.render) {
        return props.content.render;
    }
    if (props.render && typeof props.render === 'function') {
        return props.render;
    }
}

function createPopoverInstance(options: PopoverServiceOptions): App {
    const container = document.createElement('div');
    container.style.display = 'contents';
    let popoverApp: App;
    const onClickCallback = options.onClickCallback || (() => { });
    const onClose = () => {
        onClickCallback();
        if (popoverApp) {
            popoverApp.unmount();
        }
    };
    popoverApp = createApp({
        setup() {
            onUnmounted(() => {
                document.body.removeChild(container);
            });
            const contentRender = getContentRender(options);
            return () => (
                <FPopover visible={true} placement="bottom-left"
                    reference={options.reference}
                    host={options.popupHost} keep-width-with-reference={true}
                    right-boundary={options.popupRightBoundary}
                    offsetX={options.popupOffsetX} z-index={0}
                    onHidden={onClose}>
                    {contentRender && contentRender()}
                </FPopover>
            );
        }
    });
    document.body.appendChild(container);
    popoverApp.mount(container);
    return popoverApp;
}

export default class PopoverService {

    static show(options: PopoverServiceOptions): App {
        return createPopoverInstance(options);
    }
}
